﻿




import Request from "../../base/request.js?t=202511041006"
import Storage from "../../base/storage.js?t=202511041006"
import {  downloadfun, isImageFile, DeleteModuleFile, queryURLParams, dealTime, getBrowserInfo, getRecentYears, IgetDeptList } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {

    const data = reactive({

        pdfOpen: false,
        pdfurl: "",
        messageTest: "",
        proxy: "",
        popShow: false,
        imgUrl: "",
        previewShow: false,
        isPermiss: false,
        settingList: [

        ],
        uploadImg: {
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            fileList: [

            ]
        },
        yearlist: [],
        isAll: false,
        itemRender: (data) => {
            let uid = data.file.FileId
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })
            const FDBtn = h(antd.Popconfirm, {
                title: "确定删除此文件？确定后不可恢复",
                onConfirm: () => methods.btnDelete(data)

            }, { default: () => [deleteBtn] })
            var btns = h('div', { style: "display:flex;margin-left:10px" }, {
                default: () => [
                    isImageFile(data.file.url) ? previewBtn : null,
                    downloadBtn,
                    params.urlinfo.value.type == 9 ? null : FDBtn
                ]
            })



            return h('div', { style: 'margin-top:10px; width:400px;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },
        uploadLock: false,
        deptList: [],
        formData: {

        },
        sformData: {
            Period: null,
            Years:null
        },
        PeriodList: [
            { label: '第一季度', value: 1 },
            { label: '第二季度', value: 2 },
            { label: '第三季度', value: 3 },
            { label: '第四季度', value: 4 },
        ],
        pagination: {
            total: 0,
            current: 1,
            pageSize: 50,
            loading: true,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 50,
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗
        },
        rules: {
            ReduceDescription: [{ required: true, message: '请填写新增描述', trigger: 'change' }],
            IncreaseDescription: [{ required: true, message: '请填写删除描述', trigger: 'change' }],
            Title: [{ required: true, message: '请填写标题', trigger: 'change' }],
        },
        urlinfo: {},
 
        columns: [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    return index+1
                },
            },
            {
                title: '物资名称',
                dataIndex: 'Name',
                key: 'Name',
                align: 'center'
            },
            {
                title: '责任人',
                dataIndex: 'Responsible',
                key: 'Responsible',
                align: 'center'
            },
            {
                title: '保管位置',
                dataIndex: 'Place',
                key: 'Place',
                align: 'center'
            },
            {
                title: '检查日期',
                dataIndex: 'UpdateTime',
                key: 'UpdateTime',
                align: 'center'
            },
            {
                title: '检查季度',
                dataIndex: 'Period',
                key: 'Period',
                align: 'center',
                customRender: function ({ text }) {
                    return h(antd.Tag, {
                        color: '#0070d9' 
                    }, () => text )
                }
            },
            {
                title: '物资状态',
                dataIndex: 'Result',
                key: 'Result',
                align: 'center',
                customRender: function ({ text }) {
                    return h(antd.Tag, {
                        color: text == '正常' ? '#27d870' : '#e4454b'
                    }, () => text)
                }
            },
            {
                title: '备注',
                dataIndex: 'Remark',
                key: 'Remark',
                align: 'center'
            },
        ],

        dataSource: [],
        flag: false,
    })
    let params = toRefs(data)
    const methods = {
        setVisible: (value) => {
            params.previewShow.value = value;
        },
        btnPreview: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.FileId == e)
            item.url = item.FilePath || item.url
            if (item.url.indexOf('.pdf') != -1) {
                params.pdfurl.value = item.url
                params.pdfOpen.value = true
            } else {
                params.imgUrl.value = item.url
                methods.setVisible(true)
            }
        },
        
        allPass: () => {
            params.flag.value = !params.flag.value
            for (let e of params.settingList.value) {
                e.Result = params.flag.value == false ? null : true
            }
        },
        btnDownLoad: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.FileId == e)
            item.url = item.FilePath || item.url
            const { name, url } = item
            params.uploadLock.value = true
            downloadfun(name, url).finally(() => {
                params.uploadLock.value = false
            })

        },
        getDeptList: () => {
            return new Promise(async (resolve, rej) => {
                params.deptList.value = await IgetDeptList(Request)
                //if (params.deptList.value) {
                //    resolve(1)
                //}
            })


        },
        IGetEmergencySuppliesCheckForm: () => {
            params.uploadLock.value = true
            Request({
                url: `/EmergencyPlan/GetEmergencySuppliesCheckForm`,
                method: 'post',
                data: {
                    Id: params.urlinfo.value.fid
                }
            }).then(res => {
                params.formData.value = res.Data.SuppliesInfo
                params.sformData.value.Period = res.Data.Period
                params.sformData.value.Remark = res.Data.Remark
                
                params.formData.value.user = `${res.Data.SuppliesInfo.CreateUserName}(${res.Data.UpdateUser})`
                params.formData.value.time = dealTime(res.Data.SuppliesInfo.UpdateTime, 'YYYY-MM-DD HH:mm')
                params.settingList.value = res.Data.CheckItems.map(e => {
                    e.SuppliesItemInfo.ValidDate = dealTime(e.SuppliesItemInfo.ValidDate)
                    e.SuppliesItemInfo.Remark =e.Remark
                    e.SuppliesItemInfo.Result =e.Result
                    return e.SuppliesItemInfo
                })

                params.uploadImg.value.fileList = res.Data.FileList.map(e => {
                    return {
                        url: e.FilePath,
                        FileId: e.FileId,
                        name: e.FileName
                    }
                })

            }).finally(() => {
                params.uploadLock.value = false
            })
        },
 
        btnDelete: (e) => {

            const { FileId } = e.file
            if (FileId) {
                params.uploadLock.value = true
                DeleteModuleFile(Request, FileId).then(res => {
                    params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(e => e.FileId != FileId)
                    params.messageTest.value.success(res.Msg);
                }).finally(() => {
                    params.uploadLock.value = false
                })
            }
        },
   
        handleChange: (info) => {

            let subarrys = info.fileList.filter(e => !e.old).map(e => e.originFileObj)

            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
        
                for (let e of subarrys) {
                    formData.append('file', e)
                }

                Request({
                    url: `/download/uploadfile?Path=Emergency/Supplies`,
                    method: 'post',
                    data: formData
                }).then(res => {
               
                    params.uploadImg.value.fileList = [
                        ...res.Data.map(e => {
                            const { FilePath, FileName } = e
                            e.url = FilePath
                            e.name = FileName
                            return e
                        }),
                        ...params.uploadImg.value.fileList.filter(e => e.FileId)
                    ]
                    console.log(params.uploadImg.value.fileList,'params.uploadImg.value.fileList')
                    params.uploadLock.value = false
                })

            }

        },

        filterOption: (val, type) => {
            return `${type.label}`.includes(`${val || ''}`)
        },


        onSubmit() {
            if (params.settingList.value.filter(e => e.Result!=null).map(e => e.Result).length != params.settingList.value.length) {
              return params.messageTest.value.info('请确认全部检查状态');
            }

 
            let obj = {
                filelist: params.uploadImg.value.fileList.filter(e => e.FileId).map(e => e.FileId),
                model: {
                    FormId: params.urlinfo.value.id,
                    Remark: params.sformData.value.Remark,
                    Period: params.sformData.value.Period,
                    Years: params.sformData.value.Years
                },
                items: params.settingList.value.map(e => ({
                        "ItemId": e.Id, //应急物资里层单个物品ID：“ESI-”
                        "Period": params.sformData.value.Period, //时间阶段
                        "Result": e.Result,
                        "Remark": e.Remark})
                ),
            }


            params.uploadLock.value = true

                    Request({
                        url: "/EmergencyPlan/AddSuppliesCheckForm",
                        method: 'post',
                        data: obj,
                    }).then(res => {
                        params.messageTest.value.success(res.Msg);
                        if (res.Code != -100) {
                            setTimeout(() => {
                                methods.onBack()
                            }, 800)
                        }

                    }).finally (() => {
                        params.uploadLock.value = false
                    })
          

     
        },

        onBack: () => {
            window.location.href ="/EmergencyManagement/EMList"
        },
        handleRecord: (item) => {
            methods.IGetSuppliesItemCheckRecord(item)
        },

        IGetEmergencySuppliesCheckList: () => {
            return new Promise((resolve, rej) => {
                params.uploadLock.value = true
                Request({
                    url: "/EmergencyPlan/GetEmergencySuppliesCheckList",
                    method: 'post',
                    data: {
                        Id: params.urlinfo.value.id
                    }
                }).then(res => {
                    params.formData.value = res.Data
                    params.formData.value.user = `${res.Data.CreateUserName}(${res.Data.UpdateUser})`
                    params.formData.value.time = dealTime(res.Data.UpdateTime, 'YYYY-MM-DD HH:mm')
                    params.settingList.value = res.Data.Items.map(e => {
                        e.ValidDate = dealTime(e.ValidDate)
                        return e
                    })
                    params.uploadLock.value = false
                    resolve()

                })
            })

        },


        IGetSuppliesItemCheckRecord: (item) => {
            params.uploadLock.value=true
            Request({
                url: "/EmergencyPlan/GetSuppliesItemCheckRecord",
                method: 'post',
                data: {
                    ItemId: item.Id
                },
            }).then(res => {
                params.dataSource.value = res.Data.map(e => {
                    return {
                        Name: item.Name,
                        Responsible: item.Responsible,
                        Place: item.Place,
                        UpdateTime: dealTime(e.UpdateTime, 'YYYY-MM-DD HH:mm'),
                        Period: { 1: '第一季度', 2: '第二季度', 3: '第三季度', 4: '第四季度' }[e.Period],
                        Result: e.Result == true ? '正常' : '异常',
                        Remark: e.Remark
                    }
                })
                params.popShow.value = true

            }).finally(() => {
                params.uploadLock.value = false
            })
        },





        renderTextWithTooltip:(
            text,
            maxLength = 6,
            tooltipColor = '#108ee9',
            placement = 'top',
            customStyle = {}
        ) => {
            // 校验 text 参数，确保它是一个字符串
            if (typeof text !== 'string') {
                text = String(text ?? ''); // 如果不是字符串，转换为字符串；如果是 null/undefined，则转换为空字符串
            }

            // 如果文本长度小于等于 maxLength，直接返回 span
            if (text.length <= maxLength) {
                return h('span', { style: customStyle }, text);
            }

            // 如果文本长度超过 maxLength，使用 Tooltip 包裹
            return h(antd.Tooltip, { color: tooltipColor, placement }, {
                title: () => text, // Tooltip 的提示内容
                default: () =>
                    h('span', { style: { cursor: 'pointer', ...customStyle } }, text.slice(0, maxLength)+".."), // 显示的内容
            });
        },
         getCurrentQuarter:()=> {
            const currentDate = new Date();
    const currentMonth = currentDate.getMonth() + 1;

    let quarter;
    if (currentMonth >= 1 && currentMonth <= 3) {
        quarter = 1;
    } else if (currentMonth >= 4 && currentMonth <= 6) {
        quarter = 2;
    } else if (currentMonth >= 7 && currentMonth <= 9) {
        quarter = 3;
    } else {
        quarter = 4;
             }
             return params.PeriodList.value.filter(item => item.value === quarter)[0].value;
},


        init: () => {
            getBrowserInfo().catch(err => { console.log(err) })
            params.urlinfo.value = queryURLParams()
            params.yearlist.value = getRecentYears()
            params.sformData.value.Years = dayjs().format('YYYY')
            const currentQuarter = methods.getCurrentQuarter();
            params.sformData.value.Period = currentQuarter

            let info = Storage.get('AccountInfo', true)
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {

                Storage.set('token', res.Data,true)
                methods.getDeptList()
                if (params.urlinfo.value.type) {
                    methods.IGetEmergencySuppliesCheckForm()
                } else {
                    methods.IGetEmergencySuppliesCheckList()
                }
           
            })


            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });

        },

    }

    const template = {
        pdfPopModel: {
            template: `
           <a-modal v-model:open="pdfOpen" width= "80%" title = "PDF预览" v-on:ok="pdfOpen=false" >
<div style='height:700px'>
                <embed id="pdfviewscreen" :src="pdfurl" type="application/pdf" width="100%" style="height:100%;" />

</div>
  
            </a-modal >
`,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },


        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end pr-4">
                    <a-space>


  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(1)"
  >
          <a-button  :loading="uploadLock" v-if="urlinfo.type!=9" type="primary">提交</a-button>
  </a-popconfirm>
                       
              
                        <a-button v-on:click="onBack" :loading="uploadLock">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}
export default Composition